package com.ele.server.dao;

import com.ele.model.Section;
import com.ele.model.Word;
import com.ele.shared.dto.grid.WordGridRow;

import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class WordDAO extends GenericDAO<Word> {
    public WordDAO() {
        super(Word.class);
    }

    public List<WordGridRow> getGridData() {
        List<Object[]> list = em.createQuery("SELECT e.id, e.text, e.translation, s.id, s.name FROM Word e LEFT JOIN e.section s").getResultList();

        List<WordGridRow> rows = new ArrayList<WordGridRow>(list.size());
        for (Object[] objects : list) {
            Long id = (Long) objects[0];
            String text = (String) objects[1];
            String translation = (String) objects[2];
            Long sectionId = (Long) objects[3];
            String sectionName = (String) objects[4];
            rows.add(new WordGridRow(id, text, translation, sectionId, sectionName));
        }

        return rows;
    }

    public void attachWords(Set<Long> ids, Section section) {
        StringBuilder sb = new StringBuilder();
        for (Long id : ids) {
            sb.append(",").append(id);
        }
        sb.replace(0, 1, "");

        em.getTransaction().begin();
        Query query = em.createQuery("UPDATE Word e SET e.section = :id WHERE e.id IN (" + sb.toString() + ")");
        query.setParameter("id", section);
        int rowCount = query.executeUpdate();
        em.getTransaction().commit();
    }
}
